package com.hao.gulimall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hao.common.to.es.SkuEsModel;
import com.hao.gulimall.search.config.ESconfig;
import com.hao.gulimall.search.constant.EsConstant;
import com.hao.gulimall.search.service.ProdSaveService;
import lombok.extern.slf4j.Slf4j;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author chenwenhao
 * @version 1.0.0
 * @ClassName EsSaveServiceImpl.java
 * @createTime 2021/3/23,20:36
 * @Description 保存商品信息实现类
 */
@Slf4j
@Service
public class ProdSaveServiceImpl implements ProdSaveService {
    @Autowired
    RestHighLevelClient esclient;

    @Override
    public Boolean prodUp(List<SkuEsModel> skuEsModels) throws IOException {
        //保存商品信息到ES中
        //1.建立索引，建立映射关系，见src/main/resources/product-mapping.txt

        //ES中保存数据,构建批量保存请求
        BulkRequest bulkRequest = new BulkRequest();
        for (SkuEsModel skuEsModel : skuEsModels) {
            IndexRequest index = new IndexRequest(EsConstant.PRODUCT_INDEX);
            index.id(skuEsModel.getSkuId().toString());
            String s = JSON.toJSONString(skuEsModel);
            index.source(s, XContentType.JSON);
            bulkRequest.add(index);
        }
        BulkResponse bulk = esclient.bulk(bulkRequest, ESconfig.COMMON_OPTIONS);

        //批量保存后的错误处理
        boolean b = bulk.hasFailures();
        if(!b){
            List<String> list = Arrays.stream(bulk.getItems()).map(item -> {
                return item.getId();
            }).collect(Collectors.toList());
            log.error("商品批量上架出错：{}",list);
        }
        return b;
    }
}
